'use client'

import React, { useState, useEffect } from 'react';
import { DndContext, DragEndEvent, DragOverEvent, closestCenter } from '@dnd-kit/core';
import { arrayMove } from '@dnd-kit/sortable';
import ComponentLibrary from './components/ComponentLibrary';
import CanvasArea from './components/CanvasArea';
import PreviewMode from './components/PreviewMode';
import PropertyEditor from './components/PropertyEditor';
import { ComponentConfig } from './components/DroppedComponent';

// 页面数据类型
interface PageData {
  id: number;
  name: string;
  path: string;
  content: string;
}

// 从API获取图片URL
const fetchImageUrl = async (file: File): Promise<string> => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch('/api/upload', {
      method: 'POST',
      body: formData,
    });
    
    const result = await response.json();
    
    if (result.success && result.data && result.data.url) {
      return result.data.url;
    } else {
      console.error('上传失败:', result.message);
      return '';
    }
  } catch (error) {
    console.error('上传过程中出错:', error);
    return '';
  }
};

// Default properties for each component type
const getDefaultProperties = (type: string) => {
  switch (type) {
    case 'timeline':
      return {
        timelineData: [
          { label: "2020", img: "https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev/images/1753357503725-7u84bw584t8.png" }
        ]
      };
    case 'marquee':
      return {
        direction: "left",
        speed: 20,
        images: ["https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev/images/1753357503725-7u84bw584t8.png"],
        className: "h-50 w-auto object-contain"
      };
    case 'image':
      return {
        src: "https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev/images/1753357503725-7u84bw584t8.png",
        alt: "Sample image",
        className: "w-full min-h-[600px]"
      };
    case 'carousel':
      return {
        items: [
          { src: "https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev/images/1753357503725-7u84bw584t8.png", type: "image", alt: "Logo" }
        ],
        autoplayDelay: 2000,
        width: "86%",
        autoplay: true
      };
    case 'video':
      return {
        src: "https://pub-d9c5812daa2b44e5b6d7b6621bbeb301.r2.dev/nan-an-dian.mp4",
        className: "w-full h-auto",
        objectFit: "cover",
        autoPlay: true
      };
    case 'iframe':
      return {
        src: "https://www.example.com",
        className: "w-full h-96 border rounded"
      };
    default:
      return {};
  }
};

export default function PageBuilder() {
  const [components, setComponents] = useState<ComponentConfig[]>([]);
  const [isPreviewMode, setIsPreviewMode] = useState(false);
  const [uploadedImages, setUploadedImages] = useState<{[key: string]: string}>({});
  const [selectedComponentId, setSelectedComponentId] = useState<string | null>(null);
  
  // 页面管理状态
  const [pages, setPages] = useState<PageData[]>([]);
  const [activePageId, setActivePageId] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);

  // 获取所有页面数据
  const fetchPages = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/page_manage');
      const result = await response.json();
      
      if (result.success) {
        setPages(result.data);
      } else {
        console.error('获取页面数据失败:', result.error);
      }
    } catch (error) {
      console.error('获取页面数据时出错:', error);
    } finally {
      setLoading(false);
    }
  };

  // 保存页面内容
  const savePage = async (pageId: number, content: string) => {
    try {
      setLoading(true);
      const response = await fetch('/api/page_manage', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: pageId,
          content: content,
        }),
      });
      
      const result = await response.json();
      
      if (result.success) {
        // 更新本地页面数据
        setPages(prev => prev.map(page => 
          page.id === pageId ? { ...page, content } : page
        ));
        alert('保存成功！');
      } else {
        console.error('保存失败:', result.error);
        alert('保存失败: ' + result.error);
      }
    } catch (error) {
      console.error('保存时出错:', error);
      alert('保存时出错: ' + error);
    } finally {
      setLoading(false);
    }
  };

  // 切换页面并加载内容
  const switchToPage = (pageId: number) => {
    const page = pages.find(p => p.id === pageId);
    if (page) {
      try {
        const content = JSON.parse(page.content);
        if (Array.isArray(content)) {
          setComponents(content);
        } else {
          setComponents([]);
        }
      } catch (error) {
        console.error('解析页面内容失败:', error);
        setComponents([]);
      }
      setActivePageId(pageId);
      setSelectedComponentId(null);
    }
  };

  // 保存当前编辑的页面
  const saveCurrentPage = async () => {
    if (!activePageId) {
      alert('请先选择要保存的页面');
      return;
    }
    
    const content = JSON.stringify(components);
    await savePage(activePageId, content);
  };

  // 获取当前活动页面
  const getCurrentPage = () => {
    return pages.find(p => p.id === activePageId);
  };

  // 组件初始化时获取页面数据
  useEffect(() => {
    fetchPages();
  }, []);

  // 当页面数据加载完成后，自动选择第一个页面
  useEffect(() => {
    if (pages.length > 0 && !activePageId) {
      switchToPage(pages[0].id);
    }
  }, [pages, activePageId]);

  // 处理文件上传
  const handleFileUpload = async (file: File): Promise<string> => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('folder', 'images');
      
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });
      
      const result = await response.json();
      
      if (result.success && result.data && result.data.url) {
        // 保存上传的图片URL
        setUploadedImages(prev => ({
          ...prev,
          [file.name]: result.data.url
        }));
        return result.data.url;
      } else {
        console.error('上传失败:', result.message);
        return '';
      }
    } catch (error) {
      console.error('上传过程中出错:', error);
      return '';
    }
  };

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (!over) return;

    // If dragging from component library to canvas
    if (over.id === 'canvas-area' && active.data.current?.type) {
      const componentType = active.data.current.type;
      const newComponent: ComponentConfig = {
        id: `${componentType}-${Date.now()}`,
        type: componentType,
        properties: getDefaultProperties(componentType)
      };
      setComponents(prev => [...prev, newComponent]);
      return;
    }

    // If reordering components in canvas
    if (active.id !== over.id) {
      setComponents(items => {
        const oldIndex = items.findIndex(item => item.id === active.id);
        const newIndex = items.findIndex(item => item.id === over.id);
        
        if (oldIndex !== -1 && newIndex !== -1) {
          return arrayMove(items, oldIndex, newIndex);
        }
        return items;
      });
    }
  };

  const handleDeleteComponent = (id: string) => {
    setComponents(prev => prev.filter(comp => comp.id !== id));
    // 如果删除的是当前选中的组件，清除选中状态
    if (selectedComponentId === id) {
      setSelectedComponentId(null);
    }
  };

  const handleSelectComponent = (id: string) => {
    setSelectedComponentId(id);
  };

  const handlePropertyUpdate = (properties: any) => {
    if (selectedComponentId) {
      handleEditComponent(selectedComponentId, properties);
    }
  };

  const handleEditComponent = async (id: string, properties: any) => {
    // 检查是否有文件需要上传
    if (properties.file) {
      try {
        const imageUrl = await handleFileUpload(properties.file);
        if (imageUrl) {
          // 根据组件类型更新不同的属性
          const component = components.find(comp => comp.id === id);
          if (component) {
            switch (component.type) {
              case 'image':
                properties.src = imageUrl;
                break;
              case 'timeline':
                if (properties.selectedTimelineIndex !== undefined) {
                  const index = properties.selectedTimelineIndex;
                  properties.timelineData[index].img = imageUrl;
                }
                break;
              case 'carousel':
                if (properties.selectedCarouselIndex !== undefined) {
                  const index = properties.selectedCarouselIndex;
                  properties.items[index].src = imageUrl;
                }
                break;
              case 'marquee':
                if (properties.selectedMarqueeIndex !== undefined) {
                  const index = properties.selectedMarqueeIndex;
                  properties.images[index] = imageUrl;
                }
                break;
            }
          }
        }
        // 删除临时文件属性
        delete properties.file;
        delete properties.selectedTimelineIndex;
        delete properties.selectedCarouselIndex;
        delete properties.selectedMarqueeIndex;
      } catch (error) {
        console.error('上传图片时出错:', error);
      }
    }

    setComponents(prev => 
      prev.map(comp => 
        comp.id === id ? { ...comp, properties } : comp
      )
    );
  };

  const handleExport = () => {
    const exportData = {
      components: components,
      timestamp: new Date().toISOString()
    };
    
    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'page-config.json';
    link.click();
    
    URL.revokeObjectURL(url);
  };

  const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result as string);
        if (data.components) {
          setComponents(data.components);
        }
      } catch (error) {
        alert('無效的檔案格式');
      }
    };
    reader.readAsText(file);
  };

  return (
    <div className="min-h-screen bg-gray-100">
      {/* Preview Mode */}
      {isPreviewMode && (
        <PreviewMode 
          components={components} 
          onClose={() => setIsPreviewMode(false)} 
        />
      )}

      {/* Header with Page Tabs */}
      <div className="bg-white shadow-sm border-b border-gray-200">
        {/* Top Header */}
        <div className="p-4 border-b border-gray-100">
          <div className="flex justify-between items-center">
            <div className="flex items-center space-x-4">
              <h1 className="text-2xl font-bold text-gray-900">页面管理系统</h1>
              {getCurrentPage() && (
                <span className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded">
                  当前编辑: {getCurrentPage()?.name}
                </span>
              )}
            </div>
            <div className="flex space-x-3">
              <button
                onClick={saveCurrentPage}
                className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600"
                disabled={!activePageId || loading}
              >
                {loading ? '保存中...' : '保存页面'}
              </button>
              <label className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 cursor-pointer">
                导入配置
                <input 
                  type="file" 
                  accept=".json" 
                  onChange={handleImport} 
                  className="hidden" 
                />
              </label>
              <button
                onClick={handleExport}
                className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
                disabled={components.length === 0}
              >
                导出配置
              </button>
              <button
                onClick={() => setComponents([])}
                className="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600"
                disabled={components.length === 0}
              >
                清除全部
              </button>
              <button
                onClick={fetchPages}
                className="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600"
                disabled={loading}
              >
                {loading ? '刷新中...' : '刷新'}
              </button>
            </div>
          </div>
        </div>
        
        {/* Page Tabs Navigation */}
        <div className="px-4">
          <div className="flex space-x-1 overflow-x-auto">
            {pages.map((page) => (
              <button
                key={page.id}
                onClick={() => switchToPage(page.id)}
                className={`px-6 py-3 font-medium border-b-2 transition-colors whitespace-nowrap ${
                  activePageId === page.id
                    ? 'border-blue-500 text-blue-600 bg-blue-50'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                📄 {page.name}
                <span className="ml-2 text-xs text-gray-400">({page.path})</span>
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Page Editor Content */}
      <div className="flex h-[calc(100vh-140px)]">
        {activePageId ? (
          <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
            <ComponentLibrary />
            <CanvasArea 
              components={components}
              onDeleteComponent={handleDeleteComponent}
              onEditComponent={handleEditComponent}
              selectedComponentId={selectedComponentId}
              onSelectComponent={handleSelectComponent}
            />
          </DndContext>
        ) : (
          <div className="flex-1 flex items-center justify-center">
            <div className="text-center">
              <div className="text-6xl mb-4">📝</div>
              <h2 className="text-xl font-semibold text-gray-700 mb-2">选择页面开始编辑</h2>
              <p className="text-gray-500">点击上方的页面标签开始编辑页面内容</p>
            </div>
          </div>
        )}
        <PropertyEditor 
          component={selectedComponentId ? components.find(comp => comp.id === selectedComponentId) || null : null}
          onUpdateProperties={handlePropertyUpdate}
        />
      </div>
    </div>
  );
}